<template>
  <div class="adminRelease">
    <div class="adminMsg">
      <h2>基本信息</h2>
      <el-form ref="houseReleaseRef" :inline="true" :label-position="'top'" :model="form" :rules="rules">
        <el-form-item class="inp" label="房屋标题" prop="house.title">
          <el-input v-model="form.house.title"></el-input>
        </el-form-item>

        <el-form-item label="房屋类型" prop="house.rentType">
          <el-select v-model="form.house.rentType" class="inp" placeholder="请选择房屋类型">
            <el-option label="整租" value="整租"></el-option>
            <el-option label="合租" value="合租"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="inp" label="月租金" prop="house.monthRent">
          <el-input v-model="form.house.monthRent"></el-input>
        </el-form-item>

        <el-form-item label="所在地" prop="house.city">
          <el-select v-model="form.house.city" class="inp" placeholder="请选择所在城市" @change="handleCityChange">
            <el-option label="成都" value="成都"></el-option>
            <el-option label="北京" value="北京"></el-option>
            <el-option label="上海" value="上海"></el-option>
            <el-option label="广州" value="广州"></el-option>
            <el-option label="重庆" value="重庆"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="inp" label="描述" prop="house.info">
          <el-input v-model="form.house.info" rows="5" type="textarea"></el-input>
        </el-form-item>

        <el-form-item class="inp" label="内容" prop="house.content">
          <el-input v-model="form.house.content" rows="5" type="textarea"></el-input>
        </el-form-item>

        <h2>详细信息</h2>

        <el-form-item class="inp" label="房屋面积" prop="house.capacity">
          <el-input v-model="form.house.capacity"></el-input>
        </el-form-item>

        <el-form-item label="所在区域" prop="house.area">
          <el-select v-model="form.house.area" class="inp"  filterable placeholder="请选择区域">
            <el-option
                v-for="item in communityOptions"
                :key="item"
                :label="item"
                :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="inp" label="卧室数量" prop="house.bedroom">
          <el-input v-model="form.house.bedroom"></el-input>
        </el-form-item>

        <el-form-item class="inp" label="客厅数量" prop="house.parlour">
          <el-input v-model="form.house.parlour"></el-input>
        </el-form-item>

        <el-form-item class="inp" label="卫生间数量" prop="house.toilet">
          <el-input v-model="form.house.toilet"></el-input>
        </el-form-item>

        <el-form-item label="是否有厨房" prop="house.kitchen">
          <el-select v-model="form.house.kitchen" class="inp">
            <el-option label="有厨房" value="1"></el-option>
            <el-option label="没有厨房" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否有电梯" prop="house.elevator">
          <el-select v-model="form.house.elevator" class="inp">
            <el-option label="有电梯" value="1"></el-option>
            <el-option label="没有电梯" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="inp" label="详细地址" prop="house.address">
          <el-input v-model="form.house.address"></el-input>
        </el-form-item>

        <h2>联系人信息</h2>
        <el-form-item class="inp" label="联系人姓名" prop="house.ownerName">
          <el-input v-model="form.house.ownerName"></el-input>
        </el-form-item>
        <el-form-item class="inp" label="联系人电话" prop="house.ownerPhone">
          <el-input v-model="form.house.ownerPhone"></el-input>
        </el-form-item>


        <h2>图片上传</h2>
        <div class="upload">
          <el-upload ref="uploadRef"
                     :auto-upload="false"
                     :before-upload="beforeAvatarUpload"
                     :file-list="fileList"
                     :limit="9"
                     :multiple="true"
                     :on-exceed="handleExceed"
                     :on-remove="handleRemove"
                     :on-success="handleAvatarSuccess"
                     action="http://localhost:8090/file/upload"
                     list-type="picture-card">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">
              仅支持单张图片上传，最多9张（jpg/png/webp格式，单张＜5MB）
              <el-button type="text" @click="handleUpload">上传图片</el-button>
            </div>
          </el-upload>
        </div>
        <br>
        <el-form-item>
          <el-button v-if="$route.query.id" type="primary" @click="updateForm('ruleForm')">修改房源</el-button>
          <el-button v-else type="primary" @click="submitForm('ruleForm')">发布房源</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>


<script>

import axios from "axios";

import {checkUserInfoComplete} from "@/util/user-info-check";

export default {
  name: 'AdminRelease',
  mounted() {
    //如果是从编辑页面跳转过来的，获取房子信息
    if (this.$route.query.id) {
      this.getHouseInfo()
    }else{
      this.getUserNameAndPhone()
    }
  },
  data() {
    return {
      communityOptions: [], // 区域选项
      communityMap: {
        '成都': ['温都区', '郫都区', '新都区', '双流区', '武侯区'],
        '北京': ['朝阳区', '海淀区', '西城区', '东城区'],
        '上海': ['浦东新区', '静安区', '黄浦区'],
        '杭州': ['西湖区', '上城区', '下城区'],
        '重庆': ['渝中区', '江北区', '沙坪坝区', '九龙坡区'],
      },
      imgs:[],
      form:{
        house:
            {
                title: '',
                rentType: '',
                monthRent: '',
                info: '',
                content: '',
                city: '',
                capacity:'',
                address: '',
                area: '',
                bedroom: '',
                parlour: '',
                kitchen: '',
                toilet: '',
                elevator: '',
                ownerName:'',
                ownerPhone: '',
                imgUrl: []
            },
        imgUrl: []
      },
      //表单验证规则
      rules: {
        'house.rentType': [
          { required: true, message: '请选择出租类型', trigger: 'blur' }
        ],
        'house.monthRent': [
          { required: true, message: '请输入月租金', trigger: 'blur' },
          { pattern: /^(?:[1-9][0-9]{0,3}|10000)$/, message: '只能输入1到9999的数字', trigger: 'blur' }
        ],
       'house.city': [
          { required: true, message: '请选择所属城市', trigger: 'blur' }
        ],
        'house.title': [
          { required: true, message: '请输入房子标题信息', trigger: 'blur' }
        ],
        'house.address': [
          { required: true, message: '请输入房子详细地址信息', trigger: 'blur' }
        ],
        'house.capacity': [
          { required: true, message: '请输入面积', trigger: 'blur' },
          { pattern: /^(1[0-9]{2}|200|[1-9]?[0-9])$/, message: '只能输入1到200的数字', trigger: 'blur' }
        ],
        'house.bedroom': [
          { required: true, message: '请输入卧室数量', trigger: 'blur' },
          { pattern: /^(10|[1-9])$/, message: '只能输入1到10的数字', trigger: 'blur' }
        ],
        'house.parlour': [
          { required: true, message: '请输入客厅数量', trigger: 'blur' },
          { pattern: /^(10|[0-9])$/, message: '只能输入0到10的数字', trigger: 'blur' }
        ],
        'house.kitchen': [
          { required: true, message: '请选择是否有厨房', trigger: 'blur' },
        ],
        'house.toilet': [
          { required: true, message: '请输入卫生间数量', trigger: 'blur' },
          { pattern: /^(10|[1-9])$/, message: '只能输入1到10的数字', trigger: 'blur' }
        ],
        'house.elevator': [
          { required: true, message: '请选择是否有电梯', trigger: 'blur' }
        ],
        'house.ownerName': [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' }
        ],
        'house.ownerPhone': [
          { required: true, message: '请输入联系人电话', trigger: 'blur' },
          { min: 11, max: 11, message: '长度为11位', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        'house.area': [
            { required: true, message: '请选择区域', trigger: 'blur' },
        ]
      },
      //上传图片列表
      fileList: []
    }
  },
  methods: {

    //如果是从修改页面跳转过来的，获取房子信息
    getHouseInfo() {
      const id = this.$route.query.id
      axios({
        url:"http://localhost:8090/house/getHouse/"+id,
        methods: 'get',
      }).then(async res => {
        if (res.code === '200') {
          this.$message.success(res.msg)
          this.form = res.data
          const imgUrl = this.form.house.imgUrl;
          // this.imgs = typeof imgUrl === "string" ? [imgUrl] : imgUrl;
          try {
            // 尝试解析JSON字符串（兼容数据库存储格式）
            this.imgs = typeof imgUrl === "string" ? JSON.parse(imgUrl) : imgUrl;
          } catch (e) {
            // 异常处理：如果是普通字符串格式（兼容旧数据）
            this.imgs = imgUrl ? [imgUrl] : [];
          }
          this.fileList = this.imgs.map(item=>({
            name:item.substring(item.lastIndexOf("/") + 1),
            url:item,
          }))
          /*this.fileList = this.imgs.map(url=>({
            name:url.substring(url.lastIndexOf("/")+1),
            url:url,
          }))*/
        }
      })
    },

    //获取用户名与电话
    getUserNameAndPhone(){
      axios({
        url:'/user/getUserNameAndPhone',
        method:'get'
      }).then(res=>{
        if (res.code === '200'){
          console.log("返回的数据是",res.data)
          this.form.house.ownerName = res.data.username;
          this.form.house.ownerPhone = res.data.phone;
        }else{
          this.$message.error(res.msg)
        }
      })
    },

    // 处理文件超出限制
    handleExceed(files, fileList) {
      this.$message.warning(`最多上传9张图片，当前已选择 ${files.length + fileList.length} 张`);
    },

    handleCityChange(city) {
      this.form.house.area = '';//清空区域内容
      this.communityOptions = this.communityMap[city] || []
    },

    //移除图片
    handleRemove(file,fileList) {
      this.imgs = this.imgs.filter(url => url !== file.url);
    },

    // 清空已上传的文件列表
    clearFiles() {
      this.form =''
      this.imgs=[]
    },

    //上传图片成功后的回调
    handleAvatarSuccess(res,file) {
      if (res.code === '200'){
        this.imgs.push(res.data)
      }
      console.log("当前的图片集是：",this.imgs)
    },

    //上传图片之前的验证
    beforeAvatarUpload(file) {
      const isImage = ['image/jpeg', 'image/png', 'image/webp'].includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isImage) {
        this.$message.error('只能上传JPG/PNG格式!');
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB!');
      }
      return isImage && isLt5M;
    },

    //点击上传按钮完成图片上传
    handleUpload(){
      //console.log("当前要上传的房屋图片是：",JSON.stringify(this.imgs))
      this.form.imgUrl = JSON.stringify(this.imgs)
      this.$refs.uploadRef.submit()
      //console.log("上传的imgUrl:",this.form.imgUrl)
    },

    //发布新房源
    submitForm() {
      this.$refs['houseReleaseRef'].validate((valid) => {
        if (valid) {
          // if (this.imgs.length === 0){
          //   return this.$message.warning('请上传图片!')
          // }

          this.form.house.imgUrl = JSON.stringify(this.imgs)
          //房东需要完善个人信息后才能进行发布房源
          const flag = checkUserInfoComplete();

          if (flag === false){
            return this.$message.warning('请先完善个人信息!')
          }else {
            axios({
              url: "http://localhost:8090/house/release",
              method: 'post',
              data: this.form.house
            }).then(res => {
              if (res.code === '200') {
                this.$message.success('发布成功!')
                this.clearFiles()
              } else {
                this.$message.error(res.msg);
              }
            })
          }
        }
      })
    },

    //更新房屋信息
    updateForm(){
      //console.log("当前要上传的房屋图片是：",JSON.stringify(this.imgs))
      //this.form.house.imgUrl = JSON.stringify(this.imgs);
      axios({
        url:"/house/update",
        method: 'put',
        data: {
          id:this.form.house.id,
          title:this.form.house.title,
          rentType:this.form.house.rentType,
          monthRent:this.form.house.monthRent,
          city:this.form.house.city,
          info:this.form.house.info,
          content:this.form.house.content,
          capacity:this.form.house.capacity,
          area:this.form.house.area,
          bedroom:this.form.house.bedroom,
          parlour:this.form.house.parlour,
          toilet:this.form.house.toilet,
          kitchen:this.form.house.kitchen,
          elevator:this.form.house.elevator,
          address:this.form.house.address,
          ownerName:this.form.ownerName,
          ownerPhone:this.form.ownerPhone,
          imgUrl:JSON.stringify(this.imgs)
        }
      }).then(res => {
        if (res.code === '200') {
          this.$message.success('房源更新成功!')
        } else {
          this.$message.error(res.msg);
        }
      })
    },
  },
}
</script>

<style scoped>
.adminRelease {
  width: 1110px;
  min-height: 821px;
  background-color: white;
  padding: 30px;
}

.adminMsg {
  width: 1110px;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px 100px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)
}

.adminMsg h2 {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 10px;
}

.inp {
  width: 535px;
  padding-right: 10px;
}
</style>
